import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jyofservice/bean/user_fee_info_entity.dart';
import 'package:jyofservice/bean/level_tree_data_entity.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:jyofservice/generated/json/base/json_convert_content.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/CallRecordNotification.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:jyofservice/util/RefreshBottomSheetEvent.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';

class GetSFBMPage extends StatefulWidget {
  @override
  _GetSFBMPageState createState() => _GetSFBMPageState();
}

class _GetSFBMPageState extends State<GetSFBMPage> {
  List<LevelTreeDataData?> grzlist = [];
  List<LevelTreeDataData?> hrzlist = [];
  List<LevelTreeDataData?> xqlist = [];
  List<LevelTreeDataData?> lhList = [];
  List<LevelTreeDataData?> dyList = [];
  List<LevelTreeDataData?> mphList = [];
  String? showGRZ;
  String? showHRZ;
  String? showXQ;
  String? showLH;
  String? showDY;
  String? showMPH;
  UserFeeInfoDataData? detailEntity;
  late StreamSubscription subscription;
  bool isloading = true;
  int mphitem = 0;
  StateSetter? _grzState;
  StateSetter? _hrzState;
  StateSetter? _xqState;
  StateSetter? _lhState;
  StateSetter? _dyState;
  StateSetter? _mphState;
  int index = 0;
  String? key;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    subscription = eventBus.on<RefreshBottomSheetEvent>().listen((event) {
      if (mounted) {
        setState(() {});
      }
      int index = event.index;
      switch (index) {
        case 1:
          if (_grzState != null) {
            if (mounted) {
              _grzState!(() {});
            }
          }
          break;
        case 2:
          if (_hrzState != null) {
            if (mounted) {
              _hrzState!(() {});
            }
          }
          _grzState = null;
          break;
        case 3:
          if (_lhState != null) {
            if (mounted) {
              _lhState!(() {});
            }
          }
          _hrzState = null;
          break;
        case 4:
          if (_dyState != null) {
            if (mounted) {
              _dyState!(() {});
            }
          }
          _lhState = null;
          break;
        case 5:
          if (_mphState != null) {
            if (mounted) {
              _mphState!(() {});
            }
          }
          _dyState = null;
          break;
      }
    });
    subscription.resume();
    init().then((value) {
      getGrz("");
    });
  }

  Future init() async {
    var sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: Stack(
      children: <Widget>[
        Column(
          children: <Widget>[
            AppBar(
              centerTitle: true,
              title: Text(
                '编码查询',
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(45)),
              ),
              actions: <Widget>[
                SizedBox(
                  width: 30,
                )
              ],
            ),
            Container(
              width: ScreenUtil().scaleWidth,
              height: ScreenUtil().setHeight(2),
              color: Colors.grey,
            ),
            getAddressItem(),
            Expanded(
              child: Container(),
            ),
            Container(
              color: Colors.white,
              margin: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
              alignment: Alignment.bottomCenter,
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                        decoration: BoxDecoration(
                          border: Border.all(width: 1.0, color: Colors.blue),
                          color: Colors.blue,
                        ),
                        height: 60.0,
                        child: TextButton(
                          child: Text(
                            "查询",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                          onPressed: () {
                            _chaxun();
                          },
                        )),
                  ),
                ],
              ),
            )
          ],
        ),
        Offstage(
          offstage: isloading,
          child: SpinKitFadingCircle(
            color: Colors.blue,
            size: 50.0,
          ),
        )
      ],
    ));
  }

  Widget getAddressItem() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      child: SingleChildScrollView(
          child: Column(
        children: <Widget>[
          _grzbuildItem(),
          _hrzbuildItem(),
          _xqbuildItem(),
          _lhbuildItem(),
          _dybuildItem(),
          _mphbuildItem()
        ],
      )),
    );
  }

  Widget _mphitemBuilder(int item) {
    return TextButton(
      child: Text(
        mphList[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showMPH = mphList[item]!.name;
        mphitem = item;
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _mphbuildItem() {
    return ListTile(
      title: Text(
        showMPH ?? "请选择门牌号",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '门牌',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _mphState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _mphitemBuilder(item);
                            },
                            itemCount: mphList.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: mphList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _dyitemBuilder(int item) {
    return TextButton(
      child: Text(
        dyList[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showDY = dyList[item]!.name;
        showMPH = "请选择门牌号";
        getMPHData(dyList[item]!.levela,dyList[item]!.no);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _dybuildItem() {
    return ListTile(
      title: Text(
        showDY ?? "请选择单元",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '单元',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _dyState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _dyitemBuilder(item);
                            },
                            itemCount: dyList.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: dyList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _lhbuildItem() {
    return ListTile(
      title: Text(
        showLH ?? "请选择楼号",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '楼号',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _lhState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _lhitemBuilder(item);
                            },
                            itemCount: lhList.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: lhList.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _lhitemBuilder(int item) {
    return TextButton(
      child: Text(
        lhList[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showLH = lhList[item]!.name;
        showDY = "请选择单元";
        showMPH = "请选择门牌号";
        mphList.clear();
        getDYData(lhList[item]!.levela,lhList[item]!.no);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _xqbuildItem() {
    return ListTile(
      title: Text(
        showXQ ?? "请选择小区",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '小区',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _xqState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                                itemBuilder: (context, item) {
                                  return _xqitemBuilder(item);
                                },
                                itemCount: xqlist.length,
                              ))
                        ],
                      ),
                      Offstage(
                        offstage: xqlist.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _xqitemBuilder(int item) {
    return TextButton(
      child: Text(
        xqlist[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showXQ = xqlist[item]!.name;
        showLH = '请选择楼号';
        showDY = "请选择单元";
        showMPH = "请选择门牌号";
        mphList.clear();
        dyList.clear();
        getLHData(xqlist[item]!.levela,xqlist[item]!.no);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _hrzbuildItem() {
    return ListTile(
      title: Text(
        showHRZ ?? "请选择换热站",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '换站',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _hrzState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                              child: ListView.builder(
                            itemBuilder: (context, item) {
                              return _hrzitemBuilder(item);
                            },
                            itemCount: hrzlist.length,
                          ))
                        ],
                      ),
                      Offstage(
                        offstage: hrzlist.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _hrzitemBuilder(int item) {
    return TextButton(
      child: Text(
        hrzlist[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showHRZ = hrzlist[item]!.name;
        showXQ = '请选择小区';
        showLH = "请选择楼号";
        showDY = "请选择单元";
        showMPH = "请选择门牌号";
        mphList.clear();
        dyList.clear();
        lhList.clear();
        getXQData(hrzlist[item]!.levela,hrzlist[item]!.no);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Widget _grzbuildItem() {
    return ListTile(
      title: Text(
        showGRZ ?? "请选择分公司",
        style: TextStyle(fontSize: ScreenUtil().setSp(35)),
      ),
      leading: CircleAvatar(
        backgroundColor: Colors.blue,
        child: Text(
          '分司',
          style: TextStyle(color: Colors.white),
        ),
      ),
      trailing: Icon(Icons.keyboard_arrow_right),
      onTap: () {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext context) {
              return StatefulBuilder(
                builder: (context1, state) {
                  _grzState = state;
                  return Stack(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          Expanded(
                            child: ListView.builder(
                              itemBuilder: (context, item) {
                                return _grzitemBuilder(item);
                              },
                              itemCount: grzlist.length,
                            ),
                          ),
                        ],
                      ),
                      Offstage(
                        offstage: grzlist.length > 0 ? true : false,
                        child: SpinKitFadingCircle(
                          color: Colors.blue,
                          size: 50.0,
                        ),
                      )
                    ],
                  );
                },
              );
            });
      },
    );
  }

  Widget _grzitemBuilder(int item) {
    return TextButton(
      child: Text(
        grzlist[item]!.name ?? '',
        style: TextStyle(color: Colors.black, fontSize: ScreenUtil().setSp(40)),
      ),
      onPressed: () {
        Navigator.pop(context);
        showGRZ = grzlist[item]!.name;
        showHRZ = "请选择换热站";
        showLH = "请选择楼号";
        showDY = "请选择单元";
        showMPH = "请选择门牌号";
        dyList.clear();
        mphList.clear();
        getHRZData(grzlist[item]!.levela,grzlist[item]!.no);
        if (mounted) {
          setState(() {});
        }
      },
    );
  }

  Future getGrz(String xqname) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    try {
      grzlist.clear();
      String aesData = await AesUtil.encodeBase64();
      var data = {
        "key": key,
        "levela": "A",
        "no": "A1",
        "ClientType": "phone",
        "ClientKey": aesData
      };
      print(data.toString());

      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());
      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
            LevelTreeDataEntity().fromJson(response.data)!;

        grzlist.addAll(treeSimpleDataEntity.data!);
      }
      eventBus.fire(RefreshBottomSheetEvent(1));
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getHRZData(String? level, String? no) async {
    hrzlist.clear();
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "levela": level,
      "no": no,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());

      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
            LevelTreeDataEntity().fromJson(response.data)!;

        hrzlist.addAll(treeSimpleDataEntity.data!);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      eventBus.fire(RefreshBottomSheetEvent(2));
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getXQData(String? level, String? no) async {
    xqlist.clear();
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "levela": level,
      "no": no,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());

      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
        LevelTreeDataEntity().fromJson(response.data)!;

        xqlist.addAll(treeSimpleDataEntity.data!);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      eventBus.fire(RefreshBottomSheetEvent(2));
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getLHData(String? level,String? no) async {
    lhList.clear();
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "levela": level,
      "no": no,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());

      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
        LevelTreeDataEntity().fromJson(response.data)!;

        lhList.addAll(treeSimpleDataEntity.data!);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      eventBus.fire(RefreshBottomSheetEvent(3));
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getDYData(String? level,String? no) async {
    dyList.clear();
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "levela": level,
      "no": no,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());

      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
        LevelTreeDataEntity().fromJson(response.data)!;

        dyList.addAll(treeSimpleDataEntity.data!);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      eventBus.fire(RefreshBottomSheetEvent(4));
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getMPHData(String? level,String? no) async {
    mphList.clear();
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "levela": level,
      "no": no,
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio()
          .post(WebConfig().baseUrl + "Tree/GetHouseTreeDataFast", data: data);
      print("child:" + response.data.toString());

      if (response.data["Code"] == "200") {
        LevelTreeDataEntity treeSimpleDataEntity =
        LevelTreeDataEntity().fromJson(response.data)!;

        mphList.addAll(treeSimpleDataEntity.data!);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      eventBus.fire(RefreshBottomSheetEvent(5));
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  Future getSFBMData(int item) async {
    if (mounted) {
      setState(() {
        isloading = false;
      });
    }
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    String aesData = await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "view": "vw_public_house",
      "wherestr": "House_id='" + mphList[item]!.no!+ "'",
      "sortName": "House_id",
      "sortOrder": "asc",
      "ClientType": "phone",
      "ClientKey": aesData
    };
    print(data.toString());

    try {
      Response response = await Dio().post(
          WebConfig().baseUrl + "DB/getrowdatanopage",
          data: data);
      print(json.encode(response.data));

      if (response.data["Code"] == "200") {
        detailEntity =
            JsonConvert.fromJsonAsT(response.data["Data"]["data"][0]);
      } else {
        Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
      }
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      return response.data;
    } catch (e) {
      print(e.toString());
    }
  }

  void _chaxun() {
    if (showMPH == null || showMPH == "请选择门牌号") {
      Fluttertoast.showToast(msg: "请选择相应的门牌号进行查询");
    } else {
      getSFBMData(mphitem).then((onValue) {
        if (onValue != null) {
          showInfo();
        }
      });
    }
  }

  Future showInfo() async {
    final option = await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("用户信息确认"),
            content: Text(
              "姓名：" +
                  detailEntity!.linkMan! +
                  "\n编码：" +
                  detailEntity!.sfbm! +
                  "\n地址：" +
                  detailEntity!.allName!,
              style: Theme.of(context)
                  .textTheme
                  .titleMedium
                  ?.copyWith(color: Theme.of(context).textTheme.bodySmall?.color),
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: const Text('重新选择'),
                onPressed: () {
                  Navigator.pop(context, false);
                },
              ),
              CupertinoDialogAction(
                child: const Text('确认'),
                onPressed: () {
                  //下载
                  print("确认");
                  NavigatorUtil.goBack(context);
                  Constants.eventBus.fire(
                      MenuNotification(data: detailEntity));
                  NavigatorUtil.goBack(context);
//                  Navigator.pop(context, detailEntity);
                },
              )
            ],
          );
          ;
        });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    subscription.cancel();
  }
}
